<?php
// This fires after "Xem điểm" clicked
if(isset($_GET['view_scores']))
{
	// This line is important. It is needed for "prepare_page_count.php" and "prepare_boardS.php"
	$_SESSION['whichS'] = 'view';
}

if(isset($_GET['scores_by_term']))
{
	$_SESSION['whichS'] = 'view';
	$_SESSION['view_type'] = 'by_term';
}

if(isset($_GET['scores_all']))
{
	$_SESSION['whichS'] = 'view';
	$_SESSION['view_type'] = 'all';
}

// This fires after "Đổi mật khẩu" clicked
if(isset($_GET['change_pass']))
{
	$student_id = $_SESSION['student_id'];

	// This line is important. It is needed for "prepare_page_count.php" and "prepare_boardS.php"
	$_SESSION['whichS'] = 'change';

	$_SESSION['message'] = '';
}

if(isset($_POST['action']) and $_POST['action'] == 'change_pass')
{
	$student_id = $_SESSION['student_id'];
	$old_pass = $_POST['old_pass'];
	$new_pass1 = $_POST['new_pass1'];
	$new_pass2 = $_POST['new_pass2'];
	$message = '';

	if($new_pass1 == '' or $new_pass2 == '' or $old_pass == '')
	{
		$message = 'Please fill in all fields';
	}
	else if($new_pass1 != $new_pass2)
	{
		$message = 'Two passwords don\'t match';
	}
	else if($_SESSION['password'] != $old_pass) // compare to password in session
	{
		$message = 'Old password is wrong';
	}
	else
	{
		$message = 'Password was changed successfully';
		$old_pass = mysqli_real_escape_string($link, md5($old_pass . 'qldsv'));
		$lastest_pass = mysqli_real_escape_string($link, md5($new_pass1 . 'qldsv'));
		$sql = "UPDATE sinh_vien SET mat_ma = '$lastest_pass' WHERE mat_ma = '$old_pass' AND mssv = '$student_id'";
		$result = mysqli_query($link, $sql);
		if(!$result)
		{
			$error = 'error updating password';
			include '/includes/error.html.php';
			exit();
		}

		$_SESSION['password'] = $new_pass1;
	}
	
	$_SESSION['message'] = $message;
}

if(isset($_SESSION['whichS']) and $_SESSION['whichS'] == 'view')
{
	$student_id = $_SESSION['username'];
	$sql = "SELECT mssv FROM sinh_vien WHERE mssv = '$student_id'";
	$result = mysqli_query($link, $sql);
	$num_of_rows = mysqli_num_rows($result);

	// This check maybe never happens, but it's here for security
	if($num_of_rows == 0)
	{
		$error = 'Không có sinh viên này';
		include './includes/error.html.php';
		exit();
	}

	$row = mysqli_fetch_array($result);
	$student_id = $row['mssv'];
	include 'prepare_student_information.php';

	// This line is important. It is needed for "prepare_page_count.php" and "prepare_boardS.php"
	$_SESSION['whichS'] = 'view';
}



?>